<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="茶馆名字" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入茶馆名字" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="茶馆标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入茶馆标题" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['tea:room:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['tea:room:edit']"
        >修改
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['tea:room:remove']"
        >删除
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['tea:room:export']"
        >导出
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Download"
          :disabled="multiple"
          @click="handleExportCode"
          v-hasPermi="['tea:homestay:export']"
          >导出二维码
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!-- <el-table-column label="茶馆ID" align="center" prop="id" /> -->
      <el-table-column label="茶馆名字" align="center" prop="name"/>
      <el-table-column label="茶馆封面" align="center" prop="cover" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.cover" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="轮播图" align="center" prop="imgArray" width="100">
        <template #default="scope">
          <image-preview v-for="item in scope.row.imgArray" :key="item" :src="item" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="茶馆标题" align="center" prop="title"/>
      <el-table-column label="茶馆详情" align="center" prop="content" width="120">
        <template #default="scope">
          <!-- <span v-html="scope.row.content"></span> -->
          <el-button @click="openDetail(scope.$index)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="茶馆收费" align="center" prop="price"></el-table-column>
      <!-- <el-table-column label="活动时间" align="center" prop="date" width="260">
        <template #default="scope">
          <el-date-picker
              v-if="scope.row.date"
              clearable
              v-model="scope.row.date"
              type="daterange"
              value-format="YYYY-MM-DD"
              readonly
              style="width: 230px"
          >
          </el-date-picker>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="服务标签" align="center" prop="tagArray">
        <template #default="scope">
          <el-tag v-for="tag in scope.row.tagArray" :key="tag" type="info">{{ tag }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="茶馆地址" align="center" prop="address"/>
      <el-table-column label="联系电话" align="center" prop="phone"/>
      <el-table-column label="排序" align="center" prop="orderNum"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Share" @click="handleShare(scope.row,scope.$index)">分享
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tea:room:edit']"
          >修改
          </el-button
          >
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tea:room:remove']"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改茶馆管理对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body :z-index="100" :close-on-click-modal="false">
      <el-form ref="roomRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="茶馆名字" prop="name">
          <el-input v-model="form.name" placeholder="请输入茶馆名字"/>
        </el-form-item>
        <el-form-item label="茶馆封面" prop="cover">
          <image-upload v-model="form.cover" :limit="1"/>
        </el-form-item>
        <el-form-item label="轮播图" prop="imgArray">
          <image-upload v-model="form.imgArray"/>
        </el-form-item>
        <el-form-item label="茶馆标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入茶馆标题"/>
        </el-form-item>
        <el-form-item label="茶馆详情">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="茶馆收费" prop="price">
          <el-input v-model="form.price" placeholder="请输入茶馆收费"/>
        </el-form-item>
        <!-- <el-form-item label="活动时间" prop="date">
          <el-date-picker
              clearable
              v-model="form.date"
              type="daterange"
              value-format="YYYY-MM-DD"
              placeholder="请选择活动时间"
          >
          </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item label="服务标签" prop="tagArray">
          <el-select
              v-model="form.tagArray"
              multiple
              filterable
              allow-create
              default-first-option
              :reserve-keyword="false"
              placeholder="请选择服务标签"
              style="width: 240px"
          >
            <el-option v-for="item in form.tagArray" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item> -->
        <el-form-item label="茶馆地址">
          <el-input v-model="form.address" placeholder="请输入茶馆地址" :min-height="192"/>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input type="tel" placeholder="请输入联系电话"  v-model="form.phone" :min-height="192"/>
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="茶馆图文详情" width="500px" v-model="detail">
      <div v-html="roomList[nowIndex].content"></div>
    </el-dialog>
    <el-dialog title="二维码" width="250px" align-center v-model="code">
      <div style="display: flex; flex-direction: column">
        <img :src="codeContent" alt="二维码" style="" />
        <div style="text-align: center">
          {{ roomList[nowIndex]?.name || roomList[nowIndex]?.title }}
        </div>
      </div>
      <div style="display: flex; justify-content: center; padding: 10px 0">
        <el-button type="primary" plain icon="Download" @click="downloadCode(
          codeContent,
          roomList[nowIndex]?.name || roomList[nowIndex]?.title
        )"
          >下载
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Room">
import {listRoom, getRoom, delRoom, addRoom, updateRoom} from "@/api/tea/room"
import QRCode from "qrcode"

const {proxy} = getCurrentInstance()
const {top_status} = proxy.useDict("top_status")

const roomList = ref([])
const open = ref(false)
const detail = ref(false)
const nowIndex = ref(0)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const code = ref(false);
const codeContent = ref('')
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    title: null
  },
  rules: {
    name: [{required: true, message: "茶馆名字不能为空", trigger: "blur"}],
    title: [{required: true, message: "茶馆标题不能为空", trigger: "blur"}],
    orderNum: [{required: true, message: "排序不能为空", trigger: "blur"}]
  }
})

const {queryParams, form, rules} = toRefs(data)

/** 查询茶馆管理列表 */
function getList() {
  loading.value = true
  listRoom(queryParams.value).then((response) => {
    roomList.value = response.rows
    total.value = response.total
    loading.value = false
    roomList.value.forEach((item) => {
      if (item.tagArray != "" && item.tagArray != null) item.tagArray = item.tagArray.split(",")
      if (item.date != "" && item.date != null) item.date = item.date.split(",")
      if (item.imgArray != "" && item.imgArray != null) item.imgArray = item.imgArray.split(",")
    })
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    cover: null,
    imgArray: null,
    title: null,
    content: null,
    price: null,
    date: null,
    tagArray: null,
    address: null,
    phone: null,
    orderNum: 0
  }
  proxy.resetForm("roomRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加茶馆管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRoom(_id).then((response) => {
    form.value = {
      ...response.data
    }
    if (form.value.tagArray != "" && form.value.tagArray != null) form.value.tagArray = form.value.tagArray.split(",")
    if (form.value.date != "" && form.value.date != null) form.value.date = form.value.date.split(",")
    if (form.value.imgArray != "" && form.value.imgArray != null) form.value.imgArray = form.value.imgArray.split(",")
    open.value = true
    title.value = "修改茶馆管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roomRef"].validate((valid) => {
    if (valid) {
      let post = {
        ...form.value
      }
      if (post.imgArray != null) {
        post.imgArray = Array(post.imgArray).join(",")
      }
      if (post.tagArray != null) {
        post.tagArray = Array(post.tagArray).join(",")
      }
      if (post.date != null) {
        post.date = post.date.join(",")
      }
      if (post.id != null) {
        updateRoom(post).then(() => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRoom(post).then(() => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
      .confirm('是否确认删除茶馆管理编号为"' + _ids + '"的数据项？')
      .then(function () {
        return delRoom(_ids)
      })
      .then(() => {
        getList()
        proxy.$modal.msgSuccess("删除成功")
      })
      .catch(() => {
      })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
      "tea/room/export",
      {
        ...queryParams.value
      },
      `room_${new Date().getTime()}.xlsx`
  )
}

/** 打开详情 */
function openDetail(index) {
  nowIndex.value = index
  detail.value = true
}

function handleShare(row, index) {
    let text = `${import.meta.env.VITE_DOMAIN_NAME}/room/${
      row.id
    }?type=share`
    QRCode.toDataURL(text, (err, url) => {
      nowIndex.value = index
      codeContent.value = url
      code.value = true
    })
  }

function downloadCode(url, name) {
    const image = new Image()
    image.src = url
    // 创建canvas元素
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    image.onload = () => {
      // 设置canvas大小
      canvas.width = image.width
      canvas.height = image.height + 30
      // 绘制背景色
      ctx.fillStyle = 'white' // 背景颜色
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      // 绘制图片
      ctx.drawImage(image, 0, 0, image.width, image.height)
      // 设置文字样式
      ctx.font = '16px Arial'
      ctx.fillStyle = 'black' // 文字颜色
      ctx.textAlign = 'center' // 文字居中
      // 绘制文字
      ctx.fillText(name, canvas.width / 2, image.height + 10)
      // 将canvas转换为Base64编码
      const dataURL = canvas.toDataURL('image/png')
      // 创建一个链接元素
      const link = document.createElement('a')
      link.href = dataURL
      link.download = `${name}.png` // 设置下载的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }

  function handleExportCode() {
    const _ids = ids.value
    for (let i = 0; i < _ids.length; i++) {
      let text = `${import.meta.env.VITE_DOMAIN_NAME}/activity/${
        _ids[i]
      }?type=share`
      QRCode.toDataURL(text, (err, url) => {
        const name =
          activityList.value.find(item => item.id === _ids[i])?.name ||
          activityList.value.find(item => item.id === _ids[i])?.title
        downloadCode(url, name)
      })
    }
  }

getList()
</script>
